<!-- 距离计算组件 -->
<template>
    <div class="distance-calculator">
        <div class="locations">
            <div class="location-input">
                <div class="label">起点</div>
                <location-search v-model="startAddress" @select="handleStartSelect" />
            </div>
            <div class="location-input">
                <div class="label">终点</div>
                <location-search v-model="endAddress" @select="handleEndSelect" />
            </div>
        </div>

        <div class="map-container" ref="mapContainer"></div>

        <div class="result" v-if="distance">
            <el-descriptions :column="1" border>
                <el-descriptions-item label="距离">
                    {{ formatDistance(distance.distance) }}
                </el-descriptions-item>
                <el-descriptions-item label="预计时间">
                    {{ formatDuration(distance.duration) }}
                </el-descriptions-item>
            </el-descriptions>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { calculateDistance } from '@/utils/amap'
import LocationSearch from './LocationSearch.vue'

const startAddress = ref('')
const endAddress = ref('')
const startLocation = ref<[number, number] | null>(null)
const endLocation = ref<[number, number] | null>(null)
const distance = ref<{ distance: number; duration: number } | null>(null)

// 处理起点选择
const handleStartSelect = (item: any) => {
    startLocation.value = [item.location.lng, item.location.lat]
    calculateDistanceIfPossible()
}

// 处理终点选择
const handleEndSelect = (item: any) => {
    endLocation.value = [item.location.lng, item.location.lat]
    calculateDistanceIfPossible()
}

// 计算距离
const calculateDistanceIfPossible = async () => {
    if (!startLocation.value || !endLocation.value) return

    try {
        distance.value = await calculateDistance(startLocation.value, endLocation.value)
    } catch (error) {
        console.error('计算距离失败:', error)
        distance.value = null
    }
}

// 格式化距离
const formatDistance = (meters: number) => {
    if (meters >= 1000) {
        return `${(meters / 1000).toFixed(1)} 公里`
    }
    return `${Math.round(meters)} 米`
}

// 格式化时间
const formatDuration = (seconds: number) => {
    const hours = Math.floor(seconds / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)

    if (hours > 0) {
        return `${hours} 小时 ${minutes} 分钟`
    }
    return `${minutes} 分钟`
}
</script>

<style scoped>
.distance-calculator {
    width: 100%;
}

.locations {
    display: flex;
    gap: 16px;
    margin-bottom: 16px;
}

.location-input {
    flex: 1;
}

.label {
    font-size: 14px;
    color: var(--el-text-color-primary);
    margin-bottom: 8px;
}

.map-container {
    width: 100%;
    height: 400px;
    border-radius: 4px;
    overflow: hidden;
    border: 1px solid var(--el-border-color);
    margin-bottom: 16px;
}

.result {
    margin-top: 16px;
}
</style>